package com.songshuai.webapi.permission.service.impl;

import com.songshuai.webapi.baseapi.constant.BaseConstant;
import com.songshuai.webapi.baseapi.utils.PropertiesUtil;
import com.songshuai.webapi.permission.dao.YxDepartmentLeaderMapper;
import com.songshuai.webapi.permission.dao.YxDepartmentRelationMapper;
import com.songshuai.webapi.permission.dao.YxDepartmentUserMapper;
import com.songshuai.webapi.permission.dao.YxDepartmentsMapper;
import com.songshuai.webapi.permission.dao.custom.CustomYxDepartmentsMapper;
import com.songshuai.webapi.permission.dto.po.DepartmentsanduserPojo;
import com.songshuai.webapi.permission.dto.request.DepartmentsUpdateRelationAddReqDto;
import com.songshuai.webapi.permission.dto.response.*;
import com.songshuai.webapi.permission.model.*;
import com.songshuai.webapi.permission.service.CurrentUserService;
import com.songshuai.webapi.permission.service.DepartmentsService;
import com.songshuai.webapi.permission.service.YxTLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: lhx
 * @Date: 2018/11/8 14:02
 * @Version 1.0
 */
@Service
public class DepartmentsServiceImpl implements DepartmentsService {

    @Autowired
    private YxDepartmentsMapper departmentsMapper;

    @Autowired
    private YxDepartmentUserMapper departmentUserMapper;

    @Autowired
    private CustomYxDepartmentsMapper customYxDepartmentsMapper;

    @Autowired
    private RolesServiceImpl rolesService;

    @Autowired
    private YxDepartmentRelationMapper relationMapper;

    @Autowired
    private YxTLogService yxTLogService;

    @Autowired
    private YxDepartmentLeaderMapper leaderMapper;

    @Autowired
    private CurrentUserService currentUserService;

    /**
     * 添加部门
     *
     * @param yxDepartments
     * @return
     */
    @Transactional
    @Override
    public Boolean addDepartment(YxDepartments yxDepartments) {
        //插入部门
        Date date = new Date();
        yxDepartments.setCreateTime(date);
        yxDepartments.setUpdateTime(date);
        departmentsMapper.insertSelective(yxDepartments);

        //插入日志
        yxTLogService.insertSelective(new YxTLog() {{
            setOprTbName("yx_departments");
            setOprUserId(yxDepartments.getCreateBy());
            setCreateBy(yxDepartments.getCreateBy());
            setEventType(BaseConstant.EVENT_TYPE_ADD);
            setRemark(yxDepartments.toString());
            setCreateTime(date);
            setOptDescription(String.format("用户:%s,新建部门，部门id:%s",yxDepartments.getCreateBy(),yxDepartments.getId()));
        }});

        //插入部门关系
        List<YxDepartments> parentList = new ArrayList<>();//父部门
        getParentList(yxDepartments,parentList);
        List<YxDepartmentRelation> departmentRelations = new ArrayList<>();//部门关系
        int depth = 0;
        //当前部门关系
        YxDepartmentRelation delation = new YxDepartmentRelation();
        delation.setAncestorDepartmentId(yxDepartments.getId());
        delation.setDepth(depth);
        delation.setDepartmentId(yxDepartments.getId());
        delation.setCreateTime(date);
        delation.setUpdateTime(date);
        delation.setCreateBy(yxDepartments.getCreateBy());
        delation.setUpdateBy(yxDepartments.getUpdateBy());
        departmentRelations.add(delation);
        for (YxDepartments departments : parentList) {
            depth++;
            YxDepartmentRelation yxDepartmentRelation = new YxDepartmentRelation();
            yxDepartmentRelation.setAncestorDepartmentId(departments.getId());
            yxDepartmentRelation.setDepth(depth);
            yxDepartmentRelation.setDepartmentId(yxDepartments.getId());
            yxDepartmentRelation.setCreateTime(date);
            yxDepartmentRelation.setUpdateTime(date);
            yxDepartmentRelation.setCreateBy(yxDepartments.getCreateBy());
            yxDepartmentRelation.setUpdateBy(yxDepartments.getUpdateBy());
            departmentRelations.add(yxDepartmentRelation);
        }
        int i = relationMapper.insertBatch(departmentRelations);
        return i>0;
    }

    /**
     * 递归获取父级部门
     *
     * @param yxDepartments
     * @return
     */
    private void getParentList(YxDepartments yxDepartments,List<YxDepartments> parentList) {
        YxDepartments departments = departmentsMapper.selectByEntity(new YxDepartments() {{
            setId(yxDepartments.getParentId());
            setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);
        }});
        if (null != departments) {
            parentList.add(departments);
            getParentList(departments,parentList);
        }
    }



    /**
     * 查询所有部门以及子部门
     *
     * @param id 部门id
     * @return
     */
    @Override
    public DepartmentsListResDto queryAllList(Integer id) {
        DepartmentsListResDto departmentsListResDto = departmentsMapper.selectById(id);
        //当前节点是根节点，直接返回
        if (BaseConstant.CAMPUS_LEVEL_TYPE.equals(departmentsListResDto.getCampusLevelType())) {
            return departmentsListResDto;
        }
        //否则找到根节点返回
        return getParentDepartments(departmentsListResDto);
    }




    /**
     * 根据部门id获取部门树（该树包含父级以及子集）
     * @param id 部门id
     * @return
     */
    @Override
    public DepartmentsListResDto queryParentList(Integer id) {

        //获取所有子集
        List<YxDepartments> yxDepartments = departmentsMapper.selectByEntityList(new YxDepartments() {{
            setParentId(id);
            setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);
        }});
        //属性转换
        List<DepartmentsListResDto> partListResDtos = yxDepartments.stream().map(department -> {
            DepartmentsListResDto dto = new DepartmentsListResDto();
            PropertiesUtil.copyProperties(department,dto);
            return dto;
        }).collect(Collectors.toList());
        //获取当前部门
        DepartmentChildResDto listResDto = departmentsMapper.selectEntityAndChildNumById(id);
        if (null != listResDto) {
            DepartmentsListResDto resDto = new DepartmentsListResDto();
            PropertiesUtil.copyProperties(listResDto, resDto);
            resDto.setChildList(partListResDtos);
            //当前节点是根节点，直接返回
            if (BaseConstant.CAMPUS_LEVEL_TYPE.equals(resDto.getCampusLevelType())) {
                return resDto;
            } else {
                //获取最近父根节点
                return getParentDepartments(resDto);
            }
        }
        return null;
    }


    /**
     * 递归获取父级部门并组装树
     *
     * @param departments
     * @return
     */
    private DepartmentsListResDto getParentDepartments(DepartmentsListResDto departments) {
        DepartmentsListResDto parentDepartments = departmentsMapper.selectParentByChildId(departments.getParentId());
        if (null != parentDepartments) {
            List<DepartmentsListResDto> childList = new ArrayList<>();
            childList.add(departments);
            parentDepartments.setChildList(childList);
            if (!BaseConstant.CAMPUS_LEVEL_TYPE.equals(parentDepartments.getCampusLevelType())) {
                parentDepartments = getParentDepartments(parentDepartments);
            }
        } else {
            return departments;
        }

        return parentDepartments;
    }



    /**
     * 修改部门
     *
     * @param yxDepartments
     * @return
     */
    @Override
    public Boolean updateDepartment(YxDepartments yxDepartments) {
        Date date = new Date();
        yxDepartments.setUpdateTime(date);
        YxDepartments updateBefore = departmentsMapper.selectByPrimaryKey(yxDepartments.getId());
        if (null == updateBefore){
            return false;
        }
        Boolean flag = departmentsMapper.updateByPrimaryKeySelective(yxDepartments)>0;
        //插入日志
        yxTLogService.insertSelective(new YxTLog() {{
            setOprTbName("yx_departments");
            setOprUserId(yxDepartments.getCreateBy());
            setCreateBy(yxDepartments.getCreateBy());
            setEventType(BaseConstant.EVENT_TYPE_UPDATE);
            setRemark(updateBefore.toString());
            setCreateTime(date);
            setOptDescription(String.format("用户:%s,修改部门信息，部门id:%s",yxDepartments.getUpdateBy(),yxDepartments.getId()));
        }});
        return flag;
    }

    /**
     * 获取所有部门以及部门员工
     *
     * @param id 部门id
     * @return
     */
    @Override
    public DepartmentAndUserListResDto selectDeptAndUserById(Integer id) {
        return departmentsMapper.selectDeptAndUserById(id);
    }

    /**
     * 删除部门以及子部门
     *
     * @param id 部门id
     * @return
     */
    @Override
    @Transactional
    public Boolean deleteDepartments(Integer id, Integer userId) {
        Boolean flag = false;
        DepartmentsanduserPojo departmentsanduserPojo = departmentsMapper.selectDeptUserNum(id);
        if(null == departmentsanduserPojo){
            return flag;
        }
        List<Integer> deptIds = new ArrayList<>();
        Integer userNum = getDeptIdAndUserNum(departmentsanduserPojo, deptIds, 0);
        if (userNum > 0) {
            return flag;
        } else {
            //删除部门关系
            relationMapper.deleteBatchRelation(deptIds);
            //删除部门
            flag = departmentsMapper.updateBatch(deptIds) > 0;

            //插入日志
            yxTLogService.insertSelective(new YxTLog() {{
                setOprTbName("yx_departments");
                setOprUserId(userId);
                setCreateBy(userId);
                setEventType(BaseConstant.EVENT_TYPE_UPDATE);
                setRemark(deptIds.toString());
                setCreateTime(new Date());
                setOptDescription(String.format("用户:%s,删除部门信息，部门id:%s",userId,deptIds.stream().map(String::valueOf).collect(Collectors.joining(","))));
            }});
            return flag;
        }

    }

    /**
     * 递归获取部门id以及部门人数
     *
     * @param departmentsanduserPojo
     * @param deptIds
     * @param userNum
     * @return
     */
    private Integer getDeptIdAndUserNum(DepartmentsanduserPojo departmentsanduserPojo, List<Integer> deptIds, Integer userNum) {
        deptIds.add(departmentsanduserPojo.getId());
        userNum += departmentsanduserPojo.getUserNum();
        for (DepartmentsanduserPojo departmentsAndUser : departmentsanduserPojo.getDeptList()) {
            userNum = getDeptIdAndUserNum(departmentsAndUser, deptIds, userNum);
        }
        return userNum;
    }


    /**
     * 根据实体查询
     *
     * @param yxDepartments
     * @return
     */
    @Override
    public List<YxDepartments> selectByEntityList(YxDepartments yxDepartments) {
        return departmentsMapper.selectByEntityList(yxDepartments);
    }

    /**
     * 根据部门id获取子部门集合以及子部门是否有子节点
     *
     * @param id
     * @return
     */
    @Override
    public List<DepartmentChildResDto> selectListAndChildNumById(Integer id, Integer userDepartmentId) {
//        DepartmentChildListResDto resultDto = new DepartmentChildListResDto();
//        resultDto.setUserDepartmentId(userDepartmentId);
        // 获取用户所在的部门
        YxDepartments yxDepartments = departmentsMapper.selectByPrimaryKey(userDepartmentId);
        if (null != yxDepartments){
            DepartmentsListResDto departments = new DepartmentsListResDto();
            PropertiesUtil.copyProperties(yxDepartments,departments);
            //根据当前部门，递归获取所有父级树
            DepartmentsListResDto parentDepartments = getParentDepartments(departments);
            //定义map，key为父级id，value是下一级部门
            Map<Integer,DepartmentsListResDto> map = new HashMap<>();
            getParentList(parentDepartments,map);
            DepartmentsListResDto resDto = map.get(id);
            List<DepartmentChildResDto> resDtoList = new ArrayList<>();
            if (null != resDto){
                DepartmentChildResDto result = new DepartmentChildResDto();
                PropertiesUtil.copyProperties(resDto,result);
                result.setLeaf(departmentsMapper.selectChildNumById(result.getId())<0);
                result.setUserDepartmentId(userDepartmentId);
                resDtoList.add(result);
                return resDtoList;
            }else {
                List<DepartmentChildResDto> departmentChildResDtos = departmentsMapper.selectListAndChildNumById(id);
                for (DepartmentChildResDto departmentChildResDto : departmentChildResDtos) {
                    departmentChildResDto.setUserDepartmentId(userDepartmentId);
                    resDtoList.add(departmentChildResDto);
                }
                return resDtoList;
            }

        }

        return null;
    }


    /**
     * 递归获取父级部门map
     *
     * @return
     */
    private void getParentList(DepartmentsListResDto departments, Map<Integer,DepartmentsListResDto> map) {
        if (null != departments) {
            map.put(departments.getId(),null == departments.getChildList()? null:departments.getChildList().get(0));
            getParentList(null == departments.getChildList()? null:departments.getChildList().get(0),map);
        }
    }


    /**
     * 修改部门层级关系
     * @param request
     * @return
     */
    @Transactional
    @Override
    public Boolean updateDepartmentsRelation(DepartmentsUpdateRelationAddReqDto request,Integer userId) {

        boolean flag = true;
        Integer id = request.getId();
        Date date = new Date();
        //查询部门信息，获取原部门信息
        YxDepartments yxDepartments = departmentsMapper.selectByPrimaryKey(request.getId());

        /******************修改部门***********************/
        //修改部门
        departmentsMapper.updateByPrimaryKeySelective(new YxDepartments() {{
            setId(id);
            setParentId(request.getParentId());
            setUpdateTime(date);
            setUpdateBy(userId);
        }});


        /********************删除原有关系*********************/

        //查询当前部门所有原上级部门id
        List<Integer> parentIds = relationMapper.selectParentListByDepthSort(id);
        //查询当前部门所有子部门id
        List<YxDepartmentRelation> childIds = relationMapper.selectChildList(id);

        //删除当前部门所有（原）父级部门关系
        relationMapper.deleteByDepartmentId(id);

        //删除当前子部门所有（原）父级部门关系
        List<YxDepartmentRelation> deleteChildList = new ArrayList<>();
        for (Integer parentId : parentIds) {
            for (YxDepartmentRelation child : childIds) {
                YxDepartmentRelation deleteChild = new YxDepartmentRelation();
                deleteChild.setDepartmentId(child.getDepartmentId());
                deleteChild.setAncestorDepartmentId(parentId);
                deleteChildList.add(deleteChild);
            }
        }
        if (!CollectionUtils.isEmpty(deleteChildList)){
            relationMapper.deleteBatch(deleteChildList);
        }

        /*******************添加新关系*********************/

        //添加当前部门所有新父级关系
        //获取新父部门的父级集合
        List<YxDepartmentRelation> parentDepartmentRelations = relationMapper.selectByEntityList(new YxDepartmentRelation() {{
            setDepartmentId(request.getParentId());
        }});
        List<YxDepartmentRelation> addList = new ArrayList<>();
        for (YxDepartmentRelation parentDepartmentRelation : parentDepartmentRelations) {
            YxDepartmentRelation newParentRelation = new YxDepartmentRelation();
            newParentRelation.setDepartmentId(id);
            newParentRelation.setAncestorDepartmentId(parentDepartmentRelation.getAncestorDepartmentId());
            newParentRelation.setDepth(parentDepartmentRelation.getDepth()+1);
            newParentRelation.setCreateTime(date);
            newParentRelation.setCreateBy(userId);
            newParentRelation.setUpdateTime(date);
            newParentRelation.setUpdateBy(userId);
            addList.add(newParentRelation);
            //为当前部门所有子部门添加新的父部门关系
            for (YxDepartmentRelation child : childIds) {
                YxDepartmentRelation newChildParentRelation = new YxDepartmentRelation();
                newChildParentRelation.setDepartmentId(child.getDepartmentId());
                newChildParentRelation.setAncestorDepartmentId(parentDepartmentRelation.getAncestorDepartmentId());
                newChildParentRelation.setDepth(child.getDepth()+newParentRelation.getDepth());//子部门深度=子部门和当前部门之间的深度+当前部门和父级之间的深度
                newChildParentRelation.setCreateTime(date);
                newChildParentRelation.setCreateBy(userId);
                newChildParentRelation.setUpdateTime(date);
                newChildParentRelation.setUpdateBy(userId);
                addList.add(newChildParentRelation);
            }

        }
        if (!CollectionUtils.isEmpty(addList)){
            flag = relationMapper.insertBatch(addList)>0;
        }

        /******************插入日志***********************/
        yxTLogService.insertSelective(new YxTLog() {{
            setOprTbName("yx_departments");
            setOprUserId(userId);
            setCreateBy(userId);
            setEventType(BaseConstant.EVENT_TYPE_UPDATE_AND_DELETE);
            setRemark(yxDepartments.toString());
            setCreateTime(date);
            setOptDescription(String.format("用户:%s,修改部门关系，部门id:%s,原部门父级id:%s,修改后的父部门id:%s",userId,id,yxDepartments.getParentId(),request.getParentId()));
        }});

        return flag;
    }

    @Override
    public List<DepartmentsChildResDto> selectDepartmentInfoByDeptIds(String deptIds) {
        // 查询部门信息
        List<DepartmentsChildResDto> departmentsList = customYxDepartmentsMapper.selectDepartmentsList(deptIds);
        return departmentsList;
    }

    @Override
    public List<DepartmentsChildResDto> selectChildDepartments(Integer userId, Integer deptId) {
        List<DepartmentsChildResDto> list = new ArrayList<>();
        Set<String> onlineDeptIds = new HashSet<>();//线上部门集合
        Set<String> offlineDeptIds = new HashSet<>();//线下部门集合
        List<Map> departmentList = customYxDepartmentsMapper.selectDepartmentListByUserId(userId);//查询当前用户所在部门集合
        List<DepartmentsChildResDto> childDepartmentList = customYxDepartmentsMapper.selectChildDepartmentList(deptId);//查询该部门下直属部门
        if(currentUserService.CheckIsSysAdmin()){//如果超级管理员，直接返回该部门下直属部门
            return childDepartmentList;
        }
        for(Map department : departmentList){
            Integer id = (Integer) department.get("id");
            if(id == 1){//所属部门有根部门，并且是部门领导，直接返回
                YxDepartmentLeader yxDepartmentLeader = leaderMapper.selectByEntity(new YxDepartmentLeader() {{
                    setUserId(Long.valueOf(userId));
                    setDepartmentId(1);
                    setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);
                }});
                if(null != yxDepartmentLeader){
                    return childDepartmentList;
                }
            }
            String path = customYxDepartmentsMapper.selectPathByDeptId(id);//树节点
            if(StringUtils.hasText(path)){
                List<String> idList = (List<String>)Arrays.asList(path.split("-"));
                Set<String> deptIds = new HashSet<>();
                if(idList.contains("1")){//树路径包含1，则属于线上部门
                    deptIds = new HashSet<>(idList);
                    onlineDeptIds.addAll(deptIds);
                }else if(deptId != 1){//入参部门id不是1，认为是属于线下部门
                    deptIds = new HashSet<>(idList);
                    offlineDeptIds.addAll(deptIds);
                }else{//获取线下部门的顶级（校区）
                    offlineDeptIds.add(idList.get(0));
                }
            }
        }
        if(!CollectionUtils.isEmpty(childDepartmentList)){
            for(DepartmentsChildResDto resDto : childDepartmentList){
                String id = String.valueOf(resDto.getId());
                if(onlineDeptIds.contains(id)){//线上部门筛选，属于他的部门才返回
                    list.add(resDto);
                }
                if(offlineDeptIds.contains(id)){//线下部门筛选，属于他的部门才返回
                    list.add(resDto);
                }
            }
            if(deptId == 1 && CollectionUtils.isEmpty(offlineDeptIds)){
                return list;
            }else if(deptId == 1 && !CollectionUtils.isEmpty(offlineDeptIds)){
                String idList = offlineDeptIds.toString();
                String deptIds = idList.substring(1,idList.length() - 1);
                list.addAll(customYxDepartmentsMapper.selectDepartmentsList(deptIds));
            }else if(CollectionUtils.isEmpty(list)){
                List<Integer> parentIdList = relationMapper.selectParentIdList(deptId);
                if (!CollectionUtils.isEmpty(parentIdList)){
                    List<YxDepartmentLeader> yxDepartmentLeaders = leaderMapper.selectByDeptIds(userId,parentIdList);
                    if (!CollectionUtils.isEmpty(yxDepartmentLeaders)){//是部门领导，返回子部门
                        list.addAll(childDepartmentList);
                    }
                }
            }
        }
        return list.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public List<Map> selectDepartmentsAndUsersById(Integer userId, Integer deptId, Integer roleId) {
        List<Map> list = new ArrayList<>();
        List<Map> departmentUsers = new ArrayList<>();
        List<Map> departments = new ArrayList<>();
        // 查询子部门
        List<DepartmentsChildResDto> childDepartmentList = selectChildDepartments(userId, deptId);
        // 查询本部门员工
        List<DepartmentsChildResDto> departmentUserList = customYxDepartmentsMapper.selectDepartmentUsersList(deptId);
        // 查询指定角色下关联的用户id
        List<Integer> userIdList = rolesService.queryUserListByRoleId(roleId);
        if(!CollectionUtils.isEmpty(departmentUserList)){
            for(DepartmentsChildResDto resDto : departmentUserList){
                Integer id = resDto.getId();
                Integer parentId = resDto.getParentId();
                boolean isCheck = false;
                if(userIdList.contains(id)){
                    isCheck = true;
                }
                Map map = new HashMap();
                map.put("id",id);
                map.put("name",resDto.getTrueName());
                map.put("typeId",id);
                map.put("parentId","dept_" + parentId);
                map.put("isCheck",isCheck);
                map.put("leaf",true);
                departmentUsers.add(map);
            }
        }
        if(!CollectionUtils.isEmpty(childDepartmentList)){
            for(DepartmentsChildResDto dto : childDepartmentList){
                Integer id = dto.getId();
                Integer parentId = dto.getParentId();
                Map map = new HashMap();
                map.put("id",id);
                map.put("parentId", "dept_" + parentId);
                map.put("typeId", "dept_" + id);
                map.put("name",dto.getName());
                map.put("leaf",dto.getLeaf());
                departments.add(map);
            }
        }
        list.addAll(departmentUsers);
        list.addAll(departments);

        return list;
    }


    /**
     * 根据部门id获取最近的根节点
     * @param id 部门id
     * @return
     */
    @Override
    public DepartmentResDto queryRootParent(Integer id) {

        YxDepartments yxDepartments = departmentsMapper.selectByPrimaryKey(id);
        if (null != yxDepartments && BaseConstant.IS_DELETE_FLAG_NO == yxDepartments.getIsDelete()){
            DepartmentResDto resDto = new DepartmentResDto();
            if (yxDepartments.getIsRoot()){
                PropertiesUtil.copyProperties(yxDepartments,resDto);
            }else {
                YxDepartments parent = getParent(yxDepartments);
                PropertiesUtil.copyProperties(parent,resDto);
            }
            return resDto;
        }
        return null;
    }


    /**
     * 递归获取父级部门
     *
     * @param yxDepartments
     * @return
     */
    private YxDepartments getParent(YxDepartments yxDepartments) {
        YxDepartments departments = departmentsMapper.selectByEntity(new YxDepartments() {{
            setId(yxDepartments.getParentId());
            setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);
        }});
        if (null != departments) {
            if (!BaseConstant.CAMPUS_LEVEL_TYPE.equals(departments.getCampusLevelType())) {
                departments = getParent(departments);
            }
        } else {
            return yxDepartments;
        }

        return departments;
    }


    /**
     * 根据用户获取根部门集合
     * @param user
     * @return
     */
    @Override
    public List<DepartmentChildResDto> queryRootParentList(YxUsers user){
        //根据用户查询用户所在部门
        List<YxDepartmentUser> yxDepartmentUsers = departmentUserMapper.selectByEntityList(new YxDepartmentUser() {{
//            setUserId(user.getId());
            // TODO 这里先写死
            setUserId(2370624);
        }});
        List<DepartmentChildResDto> resultList = new ArrayList<>();
        for (YxDepartmentUser yxDepartmentUser : yxDepartmentUsers) {
            DepartmentChildResDto listResDto = departmentsMapper.selectEntityAndChildNumById(yxDepartmentUser.getDepartmentId());
            if (BaseConstant.CAMPUS_LEVEL_TYPE.equals(listResDto.getCampusLevelType())){
                listResDto.setUserDepartmentId(listResDto.getId());
                resultList.add(listResDto);
            }else {
                DepartmentChildResDto parentDepartment = getParentDepartment(listResDto);
                parentDepartment.setUserDepartmentId(listResDto.getId());
                resultList.add(parentDepartment);
            }

        }
        return resultList;
    }

    @Override
    public List<DepartmentsChildResDto> queryTopParentList(Integer userId) {
        Set<Integer> ids = new HashSet<>();
        String deptIds = "1";
        if(currentUserService.CheckIsSysAdmin()){//如果当前用户是超级管理员，直接返回根节点1
            return customYxDepartmentsMapper.selectDepartmentsList(deptIds);
        }
        List<Map> departmentList = customYxDepartmentsMapper.selectDepartmentListByUserId(userId);
        for(Map department : departmentList){
            Integer campusLevelType = (Integer) department.get("campusLevelType");
            Integer id = (Integer) department.get("id");
            if (BaseConstant.CAMPUS_LEVEL_TYPE.equals(campusLevelType)){
                ids.add(id);
            }else{
                String path = customYxDepartmentsMapper.selectPathByDeptId(id);
                Integer topId = Integer.valueOf(path.split("-")[0]);
                ids.add(topId);
            }
        }
        if(!ids.contains(1)){
            String idList = ids.toString();
            deptIds = idList.substring(1,idList.length() - 1);
        }
        List<DepartmentsChildResDto> list = customYxDepartmentsMapper.selectDepartmentsList(deptIds);
        return list;
    }

    @Override
    public List<Map> queryParentDepartmentList(Integer userId, Integer deptId) {
        Set<Integer> ids = new HashSet<>();
        List<Map> departmentList = customYxDepartmentsMapper.selectDepartmentListByUserId(userId);
        for(Map department : departmentList){
            Integer campusLevelType = (Integer) department.get("campusLevelType");
            Integer id = (Integer) department.get("id");
            if (!BaseConstant.CAMPUS_LEVEL_TYPE.equals(campusLevelType)){
                String path = customYxDepartmentsMapper.selectPathByDeptId(id);
                Integer index = path.indexOf(deptId);
                Integer pid = Integer.valueOf(path.substring(index,index + 1));

            }else{
                ids.add(id);
            }
        }
        return null;
    }

    private Integer parentDepartmentFlag(DepartmentsListResDto department, String deptIds){
        List<String> ids = Arrays.asList(deptIds);
        for(DepartmentsListResDto dto : department.getChildList()){
            if(ids.contains(dto.getId())){
                return department.getId();
            }else{
                parentDepartmentFlag(department, deptIds);
            }
        }
        return null;
    }

    /**
     * 递归获取父级部门
     *
     * @param departments
     * @return
     */
    private DepartmentChildResDto getParentDepartment(DepartmentChildResDto departments) {
        DepartmentChildResDto listResDto = departmentsMapper.selectEntityAndChildNumById(departments.getParentId());
        if (null != listResDto) {
            if (!BaseConstant.CAMPUS_LEVEL_TYPE.equals(listResDto.getCampusLevelType())) {
                listResDto = getParentDepartment(listResDto);
            }
        } else {
            return departments;
        }

        return listResDto;
    }


    @Override
    public DepartmentResDto selectByPrimaryKey(Integer id){
        YxDepartments yxDepartments = departmentsMapper.selectByPrimaryKey(id);
        DepartmentResDto resDto = new DepartmentResDto();
        PropertiesUtil.copyProperties(yxDepartments,resDto);
        return resDto;
    }

    /**
     * 补全部门关系
     * @return
     */
    @Override
    @Transactional
    public Boolean complementDeptRelation(){
        //查询所有部门
        List<YxDepartments> yxDepartments = departmentsMapper.selectByEntityList(new YxDepartments(){{setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);}});
        int num = 0;
        for (YxDepartments yxDepartment : yxDepartments) {
            //插入部门关系
            List<YxDepartments> parentList = new ArrayList<>();//父部门
            getParentList(yxDepartment,parentList);
            List<YxDepartmentRelation> departmentRelations = new ArrayList<>();//部门关系
            int depth = 0;
            //当前部门关系
            YxDepartmentRelation delation = new YxDepartmentRelation();
            delation.setAncestorDepartmentId(yxDepartment.getId());
            delation.setDepth(depth);
            delation.setDepartmentId(yxDepartment.getId());
            delation.setCreateTime(new Date());
            delation.setUpdateTime(new Date());
            delation.setCreateBy(yxDepartment.getCreateBy());
            delation.setUpdateBy(yxDepartment.getUpdateBy());
            departmentRelations.add(delation);
            num++;
            for (YxDepartments departments : parentList) {
                depth++;
                num++;
                YxDepartmentRelation yxDepartmentRelation = new YxDepartmentRelation();
                yxDepartmentRelation.setAncestorDepartmentId(departments.getId());
                yxDepartmentRelation.setDepth(depth);
                yxDepartmentRelation.setDepartmentId(yxDepartment.getId());
                yxDepartmentRelation.setCreateTime(departments.getCreateTime());
                yxDepartmentRelation.setUpdateTime(departments.getCreateTime());
                yxDepartmentRelation.setCreateBy(yxDepartment.getCreateBy());
                yxDepartmentRelation.setUpdateBy(yxDepartment.getUpdateBy());
                departmentRelations.add(yxDepartmentRelation);
            }
            int i = relationMapper.insertBatch(departmentRelations);
        }
        System.out.println("共"+yxDepartments.size()+"个有效本部");
        System.out.println("共插入"+num+"个有效本部关系");
        return true;
    }

    /**
     * 根据部门名称获取部门信息
     * @param name
     * @return
     */
    @Override
    public List<DepartmentResDto> queryDeptByName(String name,Integer num){
        List<DepartmentResDto> resDtoList = new ArrayList<>();
        //根据部门名称查询部门信息
        List<YxDepartments> yxDepartments = departmentsMapper.selectEntityListByName(name, num);
        if (currentUserService.CheckIsSysAdmin()){//如果当前用户是超级管理员，不用筛选，直接返回
            for (YxDepartments yxDepartment : yxDepartments) {
                DepartmentResDto departmentResDto = new DepartmentResDto();
                PropertiesUtil.copyProperties(yxDepartment,departmentResDto);
                resDtoList.add(departmentResDto);
            }
            return resDtoList;
        }

        if(!CollectionUtils.isEmpty(yxDepartments)){
            //获取该用户所在部门
            List<YxDepartments> userDepts = departmentsMapper.selectDeptByUserId(currentUserService.getUserId());
            Set<Integer> userAllDeptSet = new HashSet<>();//用户所能看到的部门id集合
            if (!CollectionUtils.isEmpty(userDepts)){
                for (YxDepartments userDept : userDepts) {
                    String path = customYxDepartmentsMapper.selectPathByDeptId(userDept.getId());
                    String[] split = path.split("-");//父级部门id
                    for (String s : split) {
                        userAllDeptSet.add(Integer.valueOf(s));//将父级添加到集合
                    }
                    //查询是否是部门领导
                    List<YxDepartmentLeader> yxDepartmentLeaders = leaderMapper.selectByDeptIds(currentUserService.getUserId(),new ArrayList<>(userAllDeptSet));
                    if (!CollectionUtils.isEmpty(yxDepartmentLeaders)){//如果是部门领导，可以查询子部门
                        //查询部门的子部门id
                        List<YxDepartmentRelation> departmentRelations = relationMapper.selectByEntityList(new YxDepartmentRelation() {{
                            setAncestorDepartmentId(userDept.getId());
                        }});
                        if (!CollectionUtils.isEmpty(departmentRelations)){
                            //子部门id添加到集合
                            Set<Integer> childIds = departmentRelations.stream().map(x -> x.getDepartmentId()).collect(Collectors.toSet());
                            userAllDeptSet.addAll(childIds);
                        }
                    }
                }
            }
            //如果包含，则可以返回
            for (YxDepartments yxDepartment : yxDepartments) {
                if (userAllDeptSet.contains(yxDepartment.getId())){
                    DepartmentResDto departmentResDto = new DepartmentResDto();
                    PropertiesUtil.copyProperties(yxDepartment,departmentResDto);
                    resDtoList.add(departmentResDto);
                }
            }
            return resDtoList;
        }
        return null;
    }


    /**
     * 根据部门id查询父级部门集合
     * @param id
     * @return
     */
    @Override
    public List<DepartmentResDto> queryParentDeptById(Integer id){
        List<DepartmentResDto> resDtoList = new ArrayList<>();
        String path = customYxDepartmentsMapper.selectPathByDeptId(id);
        String[] split = path.split("-");//父级部门id
        int depth = 1;//深度
        for (String parentId : split) {
            DepartmentResDto departmentResDto = new DepartmentResDto();
            YxDepartments yxDepartments = departmentsMapper.selectByPrimaryKey(Integer.valueOf(parentId));
            PropertiesUtil.copyProperties(yxDepartments,departmentResDto);
            departmentResDto.setDepth(depth);
            resDtoList.add(departmentResDto);
            depth++;
        }
        return resDtoList;
    }

}
